﻿#region License

//
// Author: Javier Lozano <javier@lozanotek.com>
// Copyright (c) 2009-2010, lozanotek, inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#endregion

namespace MvcTurbine.Web.Blades {
    using System.Web;
    using ComponentModel;
    using MvcTurbine.Blades;

    /// <summary>
    /// Default <see cref="IBlade"/> that supports all ASP.NET components.        
    /// </summary>
    public class WebBlade : Blade, ISupportAutoRegistration {
        #region ISupportAutoRegistration Members

        /// <summary>
        /// Provides the auto-registration of MVC related components (controllers, view engines, filters, etc).
        /// </summary>
        /// <param name="registrationList"></param>
        public void AddRegistrations(AutoRegistrationList registrationList) {
            registrationList.Add(Registration.Simple<IHttpModule>());
        }

        /// <summary>
        /// Initializes the components that are part of this blade when the rother starts up.
        /// </summary>
        /// <param name="context"></param>
        public override void Initialize(IRotorContext context) {
            base.Initialize(context);
            InitializeModules(context);
        }

        /// <summary>
        /// Starts the current blade instance.
        /// </summary>
        /// <param name="context"></param>
        public override void Spin(IRotorContext context) {
            //Do nothing here
        }

        #endregion

        /// <summary>
        /// Initializes any <see cref="IHttpModule"/> from the <see cref="IServiceLocator"/> instance.
        /// </summary>
        public virtual void InitializeModules(IRotorContext context) {
            var modules = context.ServiceLocator.ResolveServices<IHttpModule>();
            if (modules == null) return;

            var application = context.Application as HttpApplication;
            if (application == null) return;

            foreach (var module in modules) {
                module.Init(application);
            }
        }
    }
}